#!/bin/bash

# check command line argument
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 input_LLVM_IR" >&2
  exit 1
fi

if [ ! -f $1 ]; then
  echo "input LLVM IR $1 is not valid" >&2
  exit 1
fi

# tools search priority:
# 1) $HCC_HOME
# 2) @LLVM_TOOLS_DIR@ : build directory
# 3) @CMAKE_INSTALL_PREFIX@ : default install directory

if [ -n "$HCC_HOME" ] && [ -e "$HCC_HOME" ]; then
    AS=$HCC_HOME/bin/llvm-as
    OPT=$HCC_HOME/bin/opt
    SPIRIFY=$HCC_HOME/bin/clamp-spirify
    HLC_LLC=$HCC_HOME/hlc/bin/llc
    HLC_ASM=$HCC_HOME/HSAILasm/HSAILasm
elif [ -d @LLVM_TOOLS_DIR@ ]; then
    AS=@LLVM_TOOLS_DIR@/llvm-as
    OPT=@LLVM_TOOLS_DIR@/opt
    SPIRIFY=@PROJECT_BINARY_DIR@/lib/clamp-spirify
    HLC_LLC=@PROJECT_BINARY_DIR@/hlc/bin/llc
    HLC_ASM=@PROJECT_BINARY_DIR@/HSAILasm/HSAILAsm/HSAILasm # notice the "A"
elif [ -e @CMAKE_INSTALL_PREFIX@ ]; then
    AS=@CMAKE_INSTALL_PREFIX@/bin/llvm-as
    OPT=@CMAKE_INSTALL_PREFIX@/bin/opt
    SPIRIFY=@CMAKE_INSTALL_PREFIX@/bin/clamp-spirify
    HLC_LLC=@CMAKE_INSTALL_PREFIX@/hlc/bin/llc
    HLC_ASM=@CMAKE_INSTALL_PREFIX@/HSAILasm/HSAILasm
else
    echo "ERROR: Can NOT locate HCC tools! Please specify with $HCC_HOME environmental variable." >&2
    exit 1
fi

HSA_LLVM_BIN_DIR="${BASH_SOURCE%/*}/../../llvm/bin"
if [ -d $HSA_LLVM_BIN_DIR ]; then
    HLC_LLC=$HSA_LLVM_BIN_DIR/llc
fi

INPUT=$1
SUFFIX=ll
FILENAME=${INPUT%.$SUFFIX}

$SPIRIFY $INPUT > $FILENAME.spir.ll
$OPT -O3 -dce -globaldce -S -o $FILENAME.opt.ll < $FILENAME.spir.ll
$AS -o $FILENAME.bc $FILENAME.opt.ll

$HLC_LLC -O2 -march=hsail64 -filetype=obj -o $FILENAME.brig $FILENAME.bc
$HLC_ASM -disassemble -o /dev/stdout $FILENAME.brig

# remove artifacts
rm $FILENAME.spir.ll $FILENAME.opt.ll $FILENAME.bc $FILENAME.brig
